package com.fiberhome.nas.feature.common.serializable


import androidx.navigation.NavType
import kotlinx.serialization.InternalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.json.Json
import kotlinx.serialization.serializer

/**
 * 使用 kotlinx.serialization 实现的 NavType，用于传递可序列化对象
 */
class SerializableNavType<T : Any>(
    private val serializer: KSerializer<T>
) : NavType<T>(isNullableAllowed = false) {

    // 使用单例 Json 实例，避免重复创建
    private val json = Json {
        ignoreUnknownKeys = true // 忽略未知字段，提高兼容性
        encodeDefaults = true // 编码默认值
    }

    override fun get(bundle: android.os.Bundle, key: String): T? {
        return bundle.getString(key)?.let {
            json.decodeFromString(serializer, it)
        }
    }

    override fun parseValue(value: String): T {
        return json.decodeFromString(serializer, value)
    }

    override fun put(bundle: android.os.Bundle, key: String, value: T) {
        bundle.putString(key, json.encodeToString(serializer, value))
    }

    override fun serializeAsValue(value: T): String {
        return json.encodeToString(serializer, value)
    }
}

// 便捷工厂方法
@OptIn(InternalSerializationApi::class)
inline fun <reified T : Any> serializableNavType() = SerializableNavType(T::class.serializer())
